from pygame.sprite import Group, pygame
from arkanoid_reader import Reader
from pygame.locals import *
from bar import Bar
from ball import Ball
import sys
class Game:
    cubes_group = None 
    bar_group = None
    ball_group = None
    life = 1
    ball = None
    bar = None
    screen = None
    font = None
    stage = 1
    background = [(125,0,0),(0,125,0),(0,0,125)]


    def __init__(self, stage, screen):
        self.cubes_group = Group()
        self.bar_group = Group()
        self.ball_group = Group()
        self.bar = Bar()
        self.stage = stage
        self.bar_group.add(self.bar)
        self.ball = Ball()
        self.ball_group.add(self.ball)
        reader = Reader()
        reader.read_cube_file('stage_' + str(stage))
        self.cubes_group.add(reader.cubes)
        self.screen = screen
        self.font = pygame.font.SysFont(None, 48)

    def is_done(self):
        return len(self.cubes_group) < 30

    def disqualify(self):
        self.life = self.life - 1
        self.ball.handle_mouse_click(False)

    def draw(self):
        self.screen.fill(self.background[self.stage])
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    sys.exit()
            if event.type == MOUSEMOTION:
                self.bar.move(event)
                self.ball.move(event)
            if event.type == MOUSEBUTTONDOWN:
                self.ball.handle_mouse_click(True)
        self.cubes_group.update()
        self.ball.move(None)
        self.cubes_group.draw(self.screen)
        self.ball_group.draw(self.screen)
        self.bar_group.draw(self.screen)
        self.drawText('life: %s' % (self.life), 10, 0)
        pygame.display.update()
        pygame.display.flip()

    def end_game(self):
        self.screen.fill((0,0,0))
        self.drawText('press any key', 170, 250)
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    sys.exit()
                print("restart game")
        pygame.display.update()
        pygame.display.flip()


    def handle_collisions(self):
         for cube in pygame.sprite.groupcollide( self.ball_group, self.cubes_group, 0, 0).keys():
            self.ball.collide_item(None)

         for cube in pygame.sprite.groupcollide( self.cubes_group, self.ball_group, 1, 0).keys():
            pass

         for ball in pygame.sprite.groupcollide( self.ball_group, self.bar_group, 0, 0).keys():
            self.ball.collide_item( self.bar.get_velocity() )

    def drawText(self, text,  x, y):
        textobj = self.font.render(text, 1, (255,255,255))
        textrect = textobj.get_rect()
        textrect.topleft = (x, y)
        self.screen.blit(textobj, textrect)

    def is_end(self):
        return self.life == 0
    